package cn.whb.hrm.userdetails;

import cn.whb.hrm.domain.LoginUser;
import cn.whb.hrm.domain.Permission;
import cn.whb.hrm.feign.UserInfoFeignClient;
import cn.whb.hrm.mapper.LoginUserMapper;
import cn.whb.hrm.util.AjaxResult;
import cn.whb.hrm.util.encrypt.ValidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserDetailService implements UserDetailsService{

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ValidUtils.assertNotNull(username,"用户名不能为空" );
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        AjaxResult userInfo = userInfoFeignClient.findUserInfo(loginUser.getId());
        if(userInfo.isSuccess()){
            Object resultObj = userInfo.getResultObj();
            redisTemplate.opsForValue().set("userinfo::"+username, resultObj);
            Object o = redisTemplate.opsForValue().get("userinfo::"+username);
            System.err.println(o);
        }
        if(loginUser!=null){
            List<Permission> permissions = loginUserMapper.findPermissions(loginUser.getId());
            permissions.stream().forEach(permission -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
                authorities.add(authority);
            });
        }
        User user = new User(loginUser.getUsername(),loginUser.getPassword(),authorities);
        return user;
    }
}
